﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace VSA.Applications
{
    public partial class PersonInfoForm : Form
    {
        public PersonListForm ListForm { get; set;}
        public InfoEditGuideForm GuideForm { get; set;}
        public EntranceForm Entrance { get; set; }
        public int CallType { get; set; }
        public int? PersonId { get; set; }
        public VSA.WebService.ContactPerson PersonObject { get; set; }
        public DataSet ProjectDataSet { get; set; }
        private String Function { get; set; }
        public DataTable FunctionDataSource { get; set; }
        public Boolean UpdateEnable { get; set; }
        public String FacePic { get; set; }
        public String BackPic { get; set; }


        public PersonInfoForm(int personId)
        {
            InitializeComponent();
            if (personId != 0)
            {
                this.PersonId = personId;
                this.UpdateEnable = false;
            }
            else
            {
                this.UpdateEnable = true;
                this.btnSave.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\save.png");
            }
            InitialForm();
        }

        private void PersonInfoForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.CallType == 1)
            {
                GuideForm.Show();
            }
            else if (this.CallType == 3)
            {
                Entrance.Show();
            }
            this.Dispose();
        }

        private void InitialForm()
        {
            if (this.PersonId.HasValue && this.PersonId > 0)
            {
                DataSet dsPPMapping;
                DataSet dsCPMapping;
                DataSet dsCompany;
                DataSet dsProject;
                DataSet dsFunction;

                try
                {
                    DataSet[] oInitial = WebServiceFactory.GetService().GetContactPersonInfoData(this.PersonId.Value);
                    this.PersonObject = BuildPerson(oInitial[0]);
                    dsPPMapping = oInitial[1];
                    dsCPMapping = oInitial[2];
                    dsCompany = oInitial[3];
                    dsProject = oInitial[4];
                    dsFunction = oInitial[5];
                    this.FunctionDataSource = dsFunction.Tables[0];
                }
                catch (Exception)
                {
                    MessageBox.Show(
                        "A remote operation error occur",
                        "Remote Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error
                        );
                    return;
                }

                BuildCompanyBox(dsCompany.Tables[0]);
                BuildProjectCheckBox(dsProject.Tables[0]);
                BuildFunctionBox();

                if (this.PersonObject != null)
                {
                    ShowInfo(this.PersonObject, dsCPMapping, dsPPMapping);
                    EnableController(false);
                }
            }
            else
            {
                DataSet dsCompany;
                DataSet dsProject;
                DataSet dsFunction;

                try
                {
                    DataSet[] oInitial = WebServiceFactory.GetService().GetContactPersonInitialData();
                    dsCompany = oInitial[0];
                    dsProject = oInitial[1];
                    dsFunction = oInitial[2];
                    this.FunctionDataSource = dsFunction.Tables[0];
                }
                catch (Exception)
                {
                    MessageBox.Show(
                        "A remote operation error occur",
                        "Remote Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error
                        );
                    return;
                }

                BuildCompanyBox(dsCompany.Tables[0]);
                BuildProjectCheckBox(dsProject.Tables[0]);
                BuildFunctionBox();

                this.btnDirectEmail.Visible = false;
                this.btnDirectTel.Visible = false;
                this.btnMobileTel.Visible = false;
            }
            this.btnDelete.Enabled = false;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Boolean bIsValid = true;

            if (!this.UpdateEnable)
            {
                this.btnSave.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\save.png");
                this.btnDelete.Enabled = true;
                EnableController(true);
                this.UpdateEnable = true;
            }
            else
            {
                try
                {
                    if (String.IsNullOrEmpty(this.txtFamilyName.Text.Trim()))
                    {
                        this.errorProviderObject.SetError(this.txtFamilyName, "Please Input Family Name");
                        bIsValid = false;
                    }
                    if (String.IsNullOrEmpty(this.txtlDirectEmail.Text.Trim()))
                    {
                        this.errorProviderObject.SetError(this.txtlDirectEmail, "Please Input Direct Email");
                        bIsValid = false;
                    }

                    string errorMsg = String.Empty;
                    if (!Utility.ValidateInputText4Email(this.txtlDirectEmail.Text.Trim(), true, out errorMsg))
                    {
                        this.errorProviderObject.SetError(txtlDirectEmail, errorMsg);
                    }
                    if (String.IsNullOrEmpty(this.txtDirectTelephone.Text.Trim()))
                    {
                        this.errorProviderObject.SetError(this.txtDirectTelephone, "Please Input Direct Telephone");
                        bIsValid = false;
                    }

                    if (!bIsValid)
                    {
                        return;
                    }

                    String strProjects = GetProjectList();

                    String strCompanyId=String.Empty;
                    if (this.cbCompany.Text != String.Empty)
                    {
                        VSA.WebService.Company company = new VSA.WebService.Company();
                        company.CompanyName = this.cbCompany.Text.Trim();
                        company.CreateDate = DateTime.Now;
                        company.CreateBy = OfficeHelper.GetName();
                        company.LatestUpdate = DateTime.Now;
                        strCompanyId = WebServiceFactory.GetService().AddCompany(company).ToString();
                        DataTable dt = WebServiceFactory.GetService().GetAllCompanyList().Tables[0];
                        BuildCompanyBox(dt);
                    }
                    else
                    {
                        strCompanyId = this.cbCompany.SelectedValue.ToString();
                    }

                    String strFunction = String.Empty;
                    if (this.cbFunction.Text != String.Empty)
                    {
                        VSA.WebService.Functions function = new VSA.WebService.Functions();
                        function.FunctionName = this.cbFunction.Text.Trim();
                        WebServiceFactory.GetService().AddFunction(function);
                        strFunction = this.cbFunction.Text.Trim();
                        DataTable dt = WebServiceFactory.GetService().GetAllFunctionList().Tables[0];
                        this.FunctionDataSource = dt;
                        BuildFunctionBox();
                    }
                    else
                    {
                        strFunction = this.cbFunction.SelectedValue.ToString();
                    }

                    if (this.PersonId.HasValue && this.PersonId > 0)
                    {
                        this.PersonObject.FamilyName = this.txtFamilyName.Text.Trim();
                        this.PersonObject.GivenName = this.txtGivenName.Text.Trim();
                        this.PersonObject.DirectTelephone = this.txtDirectTelephone.Text.Trim();
                        this.PersonObject.DirectEmail = this.txtlDirectEmail.Text.Trim();
                        this.PersonObject.MobileTelephone = this.txtMobileTelephone.Text.Trim();
                        this.PersonObject.Comments = this.txtComments.Text.Trim();
                        this.PersonObject.Functions = this.cbFunction.SelectedValue.ToString();
                        this.PersonObject.UpdateBy = OfficeHelper.GetName();
                        this.PersonObject.Department = this.txtDepartment.Text.Trim();
                        DataSet[] objReturn = WebServiceFactory.GetService().SaveContactPerson(this.PersonObject, strCompanyId, strProjects);

                        this.PersonObject = BuildPerson(objReturn[0]);
                        DataSet dsCP = objReturn[1];
                        DataSet dsPP = objReturn[2];

                        ShowInfo(this.PersonObject, dsCP, dsPP);
                    }
                    else
                    {
                        VSA.WebService.ContactPerson person = new VSA.WebService.ContactPerson();
                        person.FamilyName = this.txtFamilyName.Text.Trim();
                        person.GivenName = this.txtGivenName.Text.Trim();
                        person.DirectTelephone = this.txtDirectTelephone.Text.Trim();
                        person.DirectEmail = this.txtlDirectEmail.Text.Trim();
                        person.MobileTelephone = this.txtMobileTelephone.Text.Trim();
                        person.Comments = this.txtComments.Text.Trim();
                        person.Functions = strFunction;
                        person.CreateBy = OfficeHelper.GetName();
                        person.Department = this.txtDepartment.Text.Trim();
                        DataSet[] objReturn = WebServiceFactory.GetService().SaveNewContactPerson(person, strCompanyId, strProjects);

                        this.PersonObject = BuildPerson(objReturn[0]);
                        this.PersonId = this.PersonObject.PersonId;
                        DataSet dsCP = objReturn[1];
                        DataSet dsPP = objReturn[2];

                        ShowInfo(this.PersonObject, dsCP, dsPP);
                    }

                    this.btnDelete.Enabled = false;
                    this.btnSave.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\update.png");
                    this.UpdateEnable = false;
                    EnableController(false);

                    MessageBox.Show(
                        "Save successful",
                        "System Information",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information
                        );
                }
                catch (Exception)
                {
                    MessageBox.Show(
                        "A system error occur",
                        "System Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error
                        );
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.PersonId.HasValue)
            {
                DialogResult dr = MessageBox.Show(
                    "Are you sure delete this person?",
                    "Confirm",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question
                    );

                if (dr == DialogResult.Yes)
                {
                    WebServiceFactory.GetService().DeleteContactPerson(this.PersonId.Value);
                    MessageBox.Show(
                        "Delete success",
                        "System Information",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information
                    );
                    if (this.ListForm != null)
                    {
                        this.ListForm.Show();
                    }
                    else if (this.GuideForm != null)
                    {
                        this.GuideForm.Show();
                    }
                    else if (this.Entrance != null)
                    {
                        this.Entrance.Show();
                    }
                    this.Dispose();
                }
            }
            else
            {
                MessageBox.Show(
                    "No person to delete",
                    "Warning",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Warning
                    );
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            if (this.ListForm != null)
            {
                this.ListForm.Show();
            }
            else if (this.GuideForm != null)
            {
                this.GuideForm.Show();
            }
            else if (this.Entrance != null)
            {
                this.Entrance.Show();
            }
            this.Dispose();
        }

        private void btnDirectTel_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txtDirectTelephone.Text.Trim()))
            {
                Utility.ShellExecute(0, String.Empty, "skype:" + this.txtDirectTelephone.Text.Trim() + "?call", String.Empty, String.Empty, 1);
            }
        }

        private void btnMobileTel_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txtMobileTelephone.Text.Trim()))
            {
                Utility.ShellExecute(0, String.Empty, "skype:" + this.txtMobileTelephone.Text.Trim() + "?call", String.Empty, String.Empty, 1);
            }
        }

        private void btnDirectEmail_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.txtlDirectEmail.Text.Trim()))
            {
                Utility.ShellExecute(0, String.Empty, "mailto:" + this.txtlDirectEmail.Text.Trim(), String.Empty, String.Empty, 1);
            }
        }

        private void BuildCompanyBox(DataTable dt)
        {
            if (this.cbCompany.Items.Count > 0)
            {
                this.cbCompany.DataSource = null;
                this.cbCompany.Items.Clear();
            }

            this.cbCompany.DataSource = dt;
            this.cbCompany.ValueMember = "CompanyId";
            this.cbCompany.DisplayMember = "CompanyName";
        }

        public void BuildProjectCheckBox(DataTable dt)
        {
            this.plProject.Controls.Clear();
            int top = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                CheckBox newck = new CheckBox();
                newck.Font = new Font("Calibri", 12);
                newck.Tag = dt.Rows[i]["ProjectId"].ToString();
                newck.Text = dt.Rows[i]["ProjectName"].ToString();
                newck.Top = top;
                this.plProject.Controls.Add(newck);
                top += 20;
            }
        }

        public void BuildFunctionBox()
        {
            if (this.cbFunction.Items.Count > 0)
            {
                this.cbFunction.DataSource = null;
                this.cbFunction.Items.Clear();
            }

            this.cbFunction.DataSource = this.FunctionDataSource;
            this.cbFunction.ValueMember = "FunctionName";
            this.cbFunction.DisplayMember = "FunctionName";
        }

        private VSA.WebService.ContactPerson BuildPerson(DataSet ds)
        {
            VSA.WebService.ContactPerson person = new VSA.WebService.ContactPerson();

            if (ds != null)
            {
                DataTable dt = ds.Tables[0];
                person.PersonId = Convert.ToInt32(dt.Rows[0]["PersonId"]);
                person.FamilyName = dt.Rows[0]["FamilyName"].ToString();
                person.GivenName = dt.Rows[0]["GivenName"].ToString();
                person.DirectTelephone = dt.Rows[0]["DirectTelephone"].ToString();
                person.DirectEmail = dt.Rows[0]["DirectEmail"].ToString();
                person.MobileTelephone = dt.Rows[0]["MobileTelephone"].ToString();
                person.Comments = dt.Rows[0]["Comments"].ToString();
                person.Functions = dt.Rows[0]["Functions"].ToString();
                person.CreateBy = dt.Rows[0]["CreateBy"].ToString();
                person.CreateDate = Convert.ToDateTime(dt.Rows[0]["CreateDate"]);
                person.UpdateBy = dt.Rows[0]["UpdateBy"].ToString();
                person.Department = dt.Rows[0]["Department"].ToString();
                person.VisitCardFace = dt.Rows[0]["VisitCardFace"].ToString();
                person.VisitCardBack = dt.Rows[0]["VisitCardBack"].ToString();

                if (dt.Rows[0]["LatestUpdate"] != DBNull.Value)
                {
                    person.LatestUpdate = Convert.ToDateTime(dt.Rows[0]["LatestUpdate"]);
                }
                else
                {
                    person.LatestUpdate = DateTime.MinValue;
                }
            }
            return person;
        }

        private String GetProjectList()
        {
            String strProjects = String.Empty;
            foreach (Control o in this.plProject.Controls)
            {
                CheckBox ck = (CheckBox)o;

                if (ck.Checked)
                {
                    if (String.IsNullOrEmpty(strProjects))
                    {
                        strProjects = ck.Tag.ToString();
                    }
                    else
                    {
                        strProjects += "|" + ck.Tag.ToString();
                    }
                }
            }
            return strProjects;
        }

        private void llblFace_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            byte[] b = WebServiceFactory.GetService().DownloadVisitCard(this.PersonId.Value, this.FacePic);
            if (b.Length > 0)
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.FileName = this.FacePic;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    FileStream fs = new FileStream(dialog.FileName, FileMode.OpenOrCreate, FileAccess.Write);
                    fs.Write(b, 0, b.Length);
                    fs.Close();
                    MessageBox.Show("Visitcard face file download Complete!");
                }
            }
            else
            {
                MessageBox.Show("Visitcard face file is not exist!");
            }
        }

        private void llblBack_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            byte[] b = WebServiceFactory.GetService().DownloadVisitCard(this.PersonId.Value, this.BackPic);
            if (b.Length > 0)
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.FileName = this.BackPic;
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    FileStream fs = new FileStream(dialog.FileName, FileMode.OpenOrCreate, FileAccess.Write);
                    fs.Write(b, 0, b.Length);
                    fs.Close();
                    MessageBox.Show("Visitcard back file download Complete!");
                }
            }
            else
            {
                MessageBox.Show("Visitcard back file is not exist!");
            }
        }

        private void ShowInfo(VSA.WebService.ContactPerson person, DataSet cpmapping, DataSet ppmapping)
        {
            this.txtFamilyName.Text = person.FamilyName;
            this.txtGivenName.Text = person.GivenName;
            this.cbFunction.SelectedValue = person.Functions;
            this.txtDirectTelephone.Text = person.DirectTelephone;
            this.txtlDirectEmail.Text = person.DirectEmail;
            this.txtMobileTelephone.Text = person.MobileTelephone;
            this.txtComments.Text = person.Comments;
            this.lblCreateTimeData.Text = person.CreateDate.ToString();
            this.txtDepartment.Text = person.Department;

            this.FacePic = person.VisitCardFace;
            this.BackPic = person.VisitCardBack;

            AttachVisitCard(this.FacePic, this.BackPic);

            if (person.LatestUpdate != DateTime.MinValue)
            {
                this.lblLatestUpdateData.Text = person.LatestUpdate.ToString();
            }
            this.lblUpdateByData.Text = person.UpdateBy;
            this.lblCreateByData.Text = person.CreateBy;

            if (!String.IsNullOrEmpty(person.DirectTelephone))
            {
                this.btnDirectTel.Visible = true;
            }
            else
            {
                this.btnDirectTel.Visible = false;
            }
            if (!String.IsNullOrEmpty(person.MobileTelephone))
            {
                this.btnMobileTel.Visible = true;
            }
            else
            {
                this.btnMobileTel.Visible = false;
            }
            if (!String.IsNullOrEmpty(person.DirectEmail))
            {
                this.btnDirectEmail.Visible = true;
            }
            else
            {
                this.btnDirectEmail.Visible = false;
            }

            if (cpmapping != null)
            {
                this.cbCompany.SelectedValue = cpmapping.Tables[0].Rows[0]["CompanyId"].ToString();
            }
            if (ppmapping != null)
            {
                DataTable dt = ppmapping.Tables[0];

                foreach (DataRow dr in dt.Rows)
                {
                    foreach (Control o in this.plProject.Controls)
                    {
                        CheckBox ck = (CheckBox)o;

                        if (ck.Tag.ToString() == dr["ProjectId"].ToString())
                        {
                            ck.Checked = true;
                            break;
                        }
                    }
                }
            }
        }

        private void llManageFunction_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            FunctionInfoForm form = new FunctionInfoForm();
            form.ContactPersonForm = this;
            form.ShowDialog();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to create new record? \r\nall fields will be cleared.", "Confirm to exit", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                this.PersonId = 0;
                this.txtComments.Text = String.Empty;
                this.txtDirectTelephone.Text = String.Empty;
                this.txtFamilyName.Text = String.Empty;
                this.txtGivenName.Text = String.Empty;
                this.txtlDirectEmail.Text = String.Empty;
                this.txtMobileTelephone.Text = String.Empty;
                this.lblCreateByData.Text = String.Empty;
                this.lblCreateTimeData.Text = String.Empty;
                this.lblLatestUpdateData.Text = String.Empty;
                this.lblUpdateByData.Text = String.Empty;
                this.txtDepartment.Text = String.Empty;
                this.cbCompany.SelectedIndex = 0;
                this.cbFunction.SelectedIndex = 0;
                this.btnDirectEmail.Visible = false;
                this.btnDirectTel.Visible = false;
                this.btnMobileTel.Visible = false;
                this.btnDelete.Enabled = false;
                this.UpdateEnable = true;
                this.btnSave.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\save.png");

                foreach (Control o in this.plProject.Controls)
                {
                    CheckBox ck = (CheckBox)o;
                    ck.Checked = false;
                }

                EnableController(true);
            }
        }

        private void EnableController(Boolean controlStatus)
        {
            this.txtFamilyName.ReadOnly = !controlStatus;
            this.txtGivenName.ReadOnly = !controlStatus;
            this.txtDirectTelephone.ReadOnly = !controlStatus;
            this.txtlDirectEmail.ReadOnly = !controlStatus;
            this.txtMobileTelephone.ReadOnly = !controlStatus;
            this.txtComments.ReadOnly = !controlStatus;
            this.txtDepartment.ReadOnly = !controlStatus;
            this.cbFunction.Enabled = controlStatus;
            this.cbCompany.Enabled = controlStatus;
            this.plProject.Enabled = controlStatus;
        }

        private void llManageProject_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ProjectInfoForm form = new ProjectInfoForm();
            form.ContactPersonForm = this;
            form.ShowDialog();
        }

        private void llManageCard_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            VisitCardInfoForm form = new VisitCardInfoForm(this.FacePic, this.BackPic);
            form.ContactPersonForm = this;
            form.PersonId = this.PersonId.Value;
            form.FaceFileName = this.FacePic;
            form.BackFileName = this.BackPic;
            form.ShowDialog();
        }

        public void AttachVisitCard(String facePic, String backPic)
        {
            this.plVisitCard.Controls.Clear();
            if (!String.IsNullOrEmpty(facePic))
            {
                LinkLabel llbl = new LinkLabel();
                llbl.Text = facePic + " (FACE)";
                llbl.AutoSize = true;
                llbl.Font = new Font("Calibri", 12);
                llbl.LinkClicked += new LinkLabelLinkClickedEventHandler(this.llblFace_LinkClicked);
                this.plVisitCard.Controls.Add(llbl);
            }
            if (!String.IsNullOrEmpty(backPic))
            {
                LinkLabel llbl = new LinkLabel();
                llbl.Text = backPic + " (BACK)";
                llbl.AutoSize = true;
                llbl.Font = new Font("Calibri", 12);
                if (!String.IsNullOrEmpty(facePic))
                {
                    llbl.Location = new Point(0, 30);
                }
                else
                {
                    llbl.Location = new Point(0, 0);
                }
                llbl.LinkClicked += new LinkLabelLinkClickedEventHandler(this.llblBack_LinkClicked);
                this.plVisitCard.Controls.Add(llbl);
            }
        }
    }
}